package com.zhy.http.okhttp.slice;

import com.zhy.http.library.OkHttpUtils;
import com.zhy.http.library.callback.BitmapCallback;
import com.zhy.http.library.callback.FileCallBack;
import com.zhy.http.library.callback.GenericsCallback;
import com.zhy.http.library.callback.StringCallback;
import com.zhy.http.library.cookie.CookieJarImpl;
import com.zhy.http.okhttp.Constants;
import com.zhy.http.okhttp.JsonGenericsSerializator;
import com.zhy.http.okhttp.ListUserCallback;
import com.zhy.http.okhttp.User;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.ComponentContainer.LayoutConfig;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.media.image.PixelMap;
import okhttp3.Call;
import okhttp3.CookieJar;
import okhttp3.Request;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainAbilitySlice extends AbilitySlice {


    private String mBaseUrl = Constants.HTTPS + "";

    private DirectionalLayout myLayout = new DirectionalLayout(this);
    private Text text, text2;
    private Image image;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        LayoutConfig config = new LayoutConfig(LayoutConfig.MATCH_PARENT, LayoutConfig.MATCH_PARENT);
        myLayout.setLayoutConfig(config);
        myLayout.setOrientation(Component.VERTICAL);
        ShapeElement element = new ShapeElement();
        element.setShape(ShapeElement.RECTANGLE);
        element.setRgbColor(new RgbColor(255, 255, 255));
        myLayout.setBackground(element);

        text = new Text(this);
        text.setText("Hello World");
        text.setHint("HAHAHAHAHAHA");
        text.setTextColor(Color.BLACK);
        text.setMultipleLine(true);
        text.setMaxTextLines(4);
        myLayout.addComponent(text);

        image = new Image(this);
        image.setImageAndDecodeBounds(com.zhy.http.okhttp.ResourceTable.Media_icon);
        myLayout.addComponent(image);

        text2 = new Text(this);
        text2.setText("Hello World");
        text2.setTextColor(Color.BLACK);
        text2.setMultipleLine(true);
        text2.setMaxTextLines(4);
        myLayout.addComponent(text2);
        super.setUIContent(myLayout);
    }

    @Override
    public void onActive() {
        super.onActive();
        getApi();
        getImage();
        postString();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onStop() {
        super.onStop();
        OkHttpUtils.getInstance().cancelTag(this);
    }

    private void getApi() {
        String authority = "api.github.com";
        String url = Constants.HTTPS + authority;
        OkHttpUtils.get().url(url).id(100).tag(this).build().execute(new MyStringCallback());
    }

    public class MyStringCallback extends StringCallback {
        @Override
        public void onBefore(okhttp3.Request request, int id) {
            super.onBefore(request, id);
        }

        @Override
        public void onAfter(int id) {
            super.onAfter(id);
        }

        @Override
        public void onError(okhttp3.Call call, Exception e, int id) {
            if (text != null) {
                text.setText("ERROR: -->" + e.getMessage());
            }
        }

        @Override
        public void onResponse(String response, int id) {
            if (text != null) {
                text.setText(response);
            }
        }
    }

    private void postString() {
        String authority = "api.github.com";
        String url = Constants.HTTPS + authority;
        OkHttpUtils.post()
                .url(url)
                .build()
                .execute(
                        new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                if (text2 != null) {
                                    text2.setText("ERROR: -->" + e.getMessage());
                                }
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                if (text2 != null) {
                                    text2.setText(response);
                                }
                            }
                        });
    }

    public void postFile(Context context) {
        File contextDistributedDir = context.getDistributedDir();
        File file = new File(contextDistributedDir, "messenger_01.png");
        if (!file.exists()) {
            ToastDialog dialog = new ToastDialog(context);
            dialog.setDuration(1500);
            dialog.setText("文件不存在，请修改文件路径");
            dialog.show();
            return;
        }
        String url = mBaseUrl + "user!postFile";
        OkHttpUtils.postFile().file(file).url(url).build().execute(new MyStringCallback());
    }

    private void getUser() {
        String url = mBaseUrl + "user!getUser";
        OkHttpUtils.post() //
                .addParams("username", "hyman") //
                .addParams("password", "123") //
                .url(url) //
                .build() //
                .execute(
                        new GenericsCallback<User>(new JsonGenericsSerializator()) {
                            @Override
                            public void onError(Call call, Exception e, int id) {}

                            @Override
                            public void onResponse(User response, int id) {}
                        });
    }

    private void getUsers() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("name", "zhy");
        String url = mBaseUrl + "user!getUsers";
        OkHttpUtils //
                .post() //
                .url(url) //
                //                .params(params)//
                .build() //
                .execute(
                        new ListUserCallback() { //
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                //                        mTv.setText("onError:" + e.getMessage());
                            }

                            @Override
                            public void onResponse(List<User> response, int id) {
                                //                        mTv.setText("onResponse:" + response);
                            }
                        });
    }

    public void getHttpsHtml() {
        String authority = "kyfw.12306.cn";
        String url = Constants.HTTPS + authority + "/otn/";
        OkHttpUtils.get() //
                .url(url) //
                .id(101)
                .build() //
                .execute(new MyStringCallback());
    }

    private void getImage() {
        String authority = "github.githubassets.com";
        String query = "?v8";
        String url = Constants.HTTPS + authority + "/images/icons/emoji/unicode/1f947.png" + query;
        OkHttpUtils.get() //
                .url(url) //
                .tag(this) //
                .build() //
                .connTimeOut(20000)
                .readTimeOut(20000)
                .writeTimeOut(20000)
                .execute(
                        new BitmapCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {

                            }

                            @Override
                            public void onResponse(PixelMap bitmap, int id) {

                                image.setPixelMap(bitmap);
                            }
                        });
    }

    public void uploadFile(Context context) {
        File contextDistributedDir = context.getDistributedDir();
        File file = new File(contextDistributedDir, "messenger_01.png");
        if (!file.exists()) {
            ToastDialog dialog = new ToastDialog(context);
            dialog.setDuration(1500);
            dialog.setText("文件不存在，请修改文件路径");
            dialog.show();
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("username", "张鸿洋");
        params.put("password", "123");

        Map<String, String> headers = new HashMap<>();
        headers.put("APP-Key", "APP-Secret222");
        headers.put("APP-Secret", "APP-Secret111");

        String url = mBaseUrl + "user!uploadFile";

        OkHttpUtils.post() //
                .addFile("mFile", "messenger_01.png", file) //
                .params(params) //
                .headers(headers) //
                .url(url) //
                .build() //
                .execute(new MyStringCallback());
    }

    public void multiFileUpload(Context context) {
        File contextDistributedDir = context.getDistributedDir();
        File file = new File(contextDistributedDir, "messenger_01.png");
        File file2 = new File(contextDistributedDir, "test1#.txt");
        if (!file.exists()) {
            ToastDialog dialog = new ToastDialog(context);
            dialog.setDuration(1500);
            dialog.setText("文件不存在，请修改文件路径");
            dialog.show();
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("username", "张鸿洋");
        params.put("password", "123");

        String url = mBaseUrl + "user!uploadFile";
        OkHttpUtils.post() //
                .addFile("mFile", "messenger_01.png", file) //
                .addFile("mFile", "test1.txt", file2) //
                .params(params) //
                .url(url)
                .build() //
                .execute(new MyStringCallback());
    }

    public void downloadFile(Context context) {
        File contextDistributedDir = context.getDistributedDir();
        String authority = "github.com";
        String query = "?raw=true";
        String url = Constants.HTTPS + authority + "/hongyangAndroid/okhttp-utils/blob/master/okhttputils-2_4_1.jar" + query;
        OkHttpUtils //
                .get() //
                .url(url) //
                .build() //
                .execute(
                        new FileCallBack(contextDistributedDir.getPath(), "gson-2.2.1.jar") { //
                            @Override
                            public void onBefore(Request request, int id) {}

                            @Override
                            public void inProgress(float progress, long total, int id) {
                                //                        mProgressBar.setProgress((int) (100 * progress));
                                //                        Log.e(TAG, "inProgress :" + (int) (100 * progress));
                            }

                            @Override
                            public void onError(Call call, Exception e, int id) {
                                //                        Log.e(TAG, "onError :" + e.getMessage());
                            }

                            @Override
                            public void onResponse(File file, int id) {
                                //                        Log.e(TAG, "onResponse :" + file.getAbsolutePath());
                            }
                        });
    }

    public void clearSession() {
        CookieJar cookieJar = OkHttpUtils.getInstance().getOkHttpClient().cookieJar();
        if (cookieJar instanceof CookieJarImpl) {
            ((CookieJarImpl) cookieJar).getCookieStore().removeAll();
        }
    }
}
